package com.example.spring.jpa.ast.handle;

import com.example.spring.jpa.ast.AstNode;

/**
 * @author: orange
 * @create: 2023-07-22 19:31
 * @description:
 */
public abstract class AbstractOperationHandle implements GlobalOperationHandle {
    @Override
    public AstNode getAstNode(String expression) throws Exception {
        if (expression == null || expression.length() == 0) {
            return null;
        }
        int start = 0;
        if (expression.indexOf('"') == 0) {
            start = indexOf(expression, '"') + 1;
        } else if (expression.indexOf('\'') == 0) {
            start = indexOf(expression, '\'') + 1;
        }
        if (start == -1) {
            throw new RuntimeException(String.format("语法错误，%s缺少字符串引号！", expression));
        }
        return handle(expression, start);
    }

    private int indexOf(String exp, char target) {
        for (int i = 1; i < exp.length(); i++) {
            if (exp.charAt(i) == target) {
                return i;
            }
        }
        return -1;
    }

    public String indexOfOperation(String operation, int index) {
        String[] ops = operations();
        for (int i = 0; i < ops.length; i++) {
            if (operation.toUpperCase().indexOf(ops[i]) == index) {
                return ops[i];
            }
        }
        return null;
    }

    public abstract String[] operations();
}
